package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户登录
     *
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //先获取用户openid
        String openid = getOpenid(userLoginDTO);
        User user = User.builder().openid(openid).build();
        //调用dao查找数据库中是否有该用户
        user = userMapper.select(user);
        //如果没有该用户，新增该用户
        if (user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
        //创建令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //组装vo数据
        UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId()).openid(openid).token(token).build();
        return userLoginVO;
    }

    //获取openid
    private String getOpenid(UserLoginDTO userLoginDTO) {
        //根据工具类参数创建Map集合
        Map<String, String> paramMap = new HashMap<>();
        //根据微信小程序开发文档钟的小程序登录组建请求参数
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        //调用微信登录接口，返回一个json
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        //获取openid
        String openid = (String)jsonObject.get("openid");
        return openid;
    }
}
